/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wwcontrolserver;

import com.phidgets.*;
import com.phidgets.event.*;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author Michael Ferry
 */
public class MotorControlTaskServer extends TimerTask {
    private Date StartTime;
    private Date EndTime;
    
    private Date CurrentTime;
    private long EllapsedTime;
    
    private InterfaceKitPhidget MotorIFK;
    //Location of the Motor relay in the motor phidgets interface kit;
    //private int MotorDO;
    
    //Number of milliseconds to run the motor
    private long RunDuration;
    
    //Number of milliseconds for the complete cycle
    private long Period;
    
    public MotorControlTaskServer(InterfaceKitPhidget MotorIFK, Date StartTime, Date EndTime, 
            long RunDuration, long Period){
        this.StartTime=StartTime;
        this.EndTime=EndTime;
        this.RunDuration=RunDuration;
        this.Period=Period;
        this.CurrentTime = new Date();
        this.MotorIFK = MotorIFK;
        //this.MotorDO=MotorDO;
        
       System.out.println("RunDuration: " + RunDuration);
       System.out.println("Period: " + Period);       
    }
    
    @Override
    public void run() {
        CurrentTime = new Date();
        EllapsedTime = CurrentTime.getTime() - StartTime.getTime();
        
//        System.out.println("Ellapsed Time: " + (EllapsedTime));
//        System.out.println("Mod result: " + (EllapsedTime % Period));
//        if (EllapsedTime % Period < RunDuration){
//            System.out.println("on");
//        }else{
//            System.out.println("off");
//        }
        try {
            
            if (MotorIFK.isAttached()) {
                //Use the modulus function to determine if the CurrentTime falls during a motor on time. Make sure the motor is 
                //in the on state if true
                if (EllapsedTime % Period < RunDuration) {
                    //Turn the motor on
                    MotorIFK.setOutputState(WWControlServer.DCMotorDO, true);
                   
                   // System.out.println("Motor turned on");
                } else {
                    //Turn the motor off
                    MotorIFK.setOutputState(WWControlServer.DCMotorDO, false);
                    //System.out.println("Motor turned off");
                }
            }else {

                System.out.println("Motor IFK not attached at :"+CurrentTime);
            }
        } catch (PhidgetException ex) {
            System.out.println(ex);
        }
    }
}
